/*
 * User: user
 * Date: 21/12/2007
 * Time: 19:41:39
 */
package org.conann.model.services;

import org.conann.bindings.LoggedIn;
import org.conann.model.Credentials;
import org.conann.model.User;
import org.conann.model.persistence.EntityManager;
import org.conann.model.persistence.PersistenceContext;
import org.conann.model.persistence.Query;

import javax.webbeans.Produces;
import javax.webbeans.binding.Current;
import javax.webbeans.scope.SessionScoped;
import javax.webbeans.stereotype.Model;
import java.util.List;

@SessionScoped
@Model
public class Login {

    @Current private Credentials credentials;
    @PersistenceContext private EntityManager userDatabase;

    private User user;

    public void login() {
        final Query query = userDatabase.createQuery("select u from User u where u.username=:username and u.password=:password");
        List<User> results = (List<User>) query.setParameter("username", credentials.getUserName()).setParameter("password", credentials.getPassword()).getResultList();
        if (!results.isEmpty()) {
            user = results.get(0);
        }
    }

    public void logout() {
        user = null;
    }

    public boolean isLoggedIn() {
        return user != null;
    }

    @Produces
    @LoggedIn
    User getCurrentUser() {
        return user;
    }
}